import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
from torch.autograd import Variable
from torch.nn import functional as F
from torchvision import datasets, transforms


class RMMModel(nn.Module):
    def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers,
                 dropout=0.5, tie_weights=False):
        super(RMMModel, self).__init__()
        self.drop = nn.Dropout(dropout)
        self.encoder = nn.Embedding(ntoken, ninp)

        if rnn_type in ['LSTM', 'GRU']:
            self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout)
        else:
            try:
                nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type]
            except KeyError:
                raise ValueError("wrong type {}".format(rnn_type))

            self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout)

        self.decoder = nn.Linear(nhid, ntoken)

        if tie_weights:
            if nhid != ninp:
                raise ValueError("when using tie weights, nhid should = ninp")
            self.decoder.weight = self.encoder.weight

        self.init_weight()

        self.rnn_type = rnn_type
        self.nhid = nhid
        self.nlayers = nlayers

    def init_weight(self):
        init_range = 0.1
        self.encoder.weight.data.uniform_(-init_range, init_range)
        self.decoder.bias.data.fill_(0)
        self.decoder.weight.data.uniform_(-init_range, init_range)

    def forward(self, inp, hid):
        emb = self.drop(self.encoder(inp))
        output, hid = self.rnn(emb, hid)

        output = self.drop(output)

        decoded = self.decoder(output.view(
            output.size(0) * output.size(1), output.size(2)
        ))

        return decoded.view(output.size(0), output.size(1), decoded.size(1)), hid

    def init_hidden(self, batch_size):
        weight = next(self.parameters()).data
        if self.rnn_type == 'LSTM':
            return (Variable(weight.new(self.nlayers, batch_size, self.nhid).zero_()),
                    Variable(weight.new(self.nlayers, batch_size, self.nhid).zero_()),)
        else:
            return Variable(weight.new(self.nlayers, batch_size, self.nhid).zero_())


def train(epoch, model, data_loader):
    pass


if __name__ == '__main__':
    m = RMMModel('LSTM', 20000, 32, 32, 1)

